/**
 * 回溯法求矩阵中的路径
 */
public class Solution12 {

    public boolean exist(char[][] matrix, String word){
        char[] words = word.toCharArray();
        for (int i = 0; i < matrix.length; i++){
            for (int j = 0; j < matrix[0].length; j++){
                if (dfs(matrix, words, i, j, 0))
                    return true;
            }
        }
        return false;
    }

    private boolean dfs(char[][] matrix, char[] word, int i, int j, int pathLen){
        if (i >= matrix.length || i < 0 || j >= matrix[0].length || j < 0 || matrix[i][j] != word[pathLen])
            return false;
        if (pathLen == word.length - 1)
            return true;
        char tmp = matrix[i][j];
        matrix[i][j] = '/'; //将访问过的元素值暂置为'/'，节省一个visited[][]辅助数组的空间
        boolean res = dfs(matrix, word, i + 1, j, pathLen + 1) ||
                dfs(matrix, word, i - 1, j, pathLen + 1) ||
                dfs(matrix, word, i, j + 1, pathLen + 1) ||
                dfs(matrix, word, i, j - 1, pathLen + 1);
        matrix[i][j] = tmp; //本次搜索结束后需要清除标记状态
        return res;
    }

//    public static void main(String[] args){
//        Solution12 solution = new Solution12();
//        char[][] matrix = {
//                {'a', 'b', 't', 'g'},
//                {'c', 'f', 'c', 's'},
//                {'j', 'd', 'e', 'h'}
//        };
//        String word = "abtg";
//        System.out.println(solution.exist(matrix, word));
//    }
}
